package com.systop.party05.http;

import android.app.Activity;
import android.text.TextUtils;

import com.systop.party05.utils.LoggerUtil;
import com.systop.party05.utils.ToastUtils;
import com.systop.party05.view.MyProgressDialog;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;


/**
 * @author gqf
 * @deprecated 公共网络请求
 */
public class MyStringCallback extends Callback<String> {
    private Activity activity; // 当前调用对应的activity
    private MyProgressDialog myProgressDialog;
    private boolean isShowLoading;

    public MyStringCallback(Activity activity) {
        this(activity, true);
    }

    public MyStringCallback(Activity activity, boolean isShowLoading) {
        this.activity = activity;
        this.isShowLoading = isShowLoading;
        if (isShowLoading && activity != null && activity.getWindow() != null) {
            myProgressDialog = new MyProgressDialog(activity);
            myProgressDialog.show();
        }
    }

    @Override
    public String parseNetworkResponse(Response response, int id) throws Exception {
        return response.body().string();
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        dismissDialog();
        LoggerUtil.e("===onError--", e);
        onError(e.getMessage());
    }

    @Override
    public void onResponse(String response, int id) {
        dismissDialog();
        LoggerUtil.d(activity.getLocalClassName() + response);
        if (TextUtils.isEmpty(response)) {
            ToastUtils.getInstance(activity).showMessage("返回信息为空");
        } else {
            try {
                JSONObject o = new JSONObject(response);
                int status = o.getInt("status");
                String msg = "";
                if (!o.isNull("msg")) {
                    msg = o.getString("msg");
                }
                if (status == 200) {
                    onSuccess(response);
                } else {
                    onOther(response, status, msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                onError(e.getMessage());
                ToastUtils.getInstance(activity).showMessage("解析异常！");
            }
        }
    }

    public void onSuccess(String response) {
    }

    public void onOther(String response, int status, String message) {
        ToastUtils.getInstance(activity).showMessage(message);
    }

    public void onError(String error) {
        ToastUtils.getInstance(activity).showMessage(error);
    }

    public void dismissDialog() {
        if (myProgressDialog != null && isShowLoading) {
            myProgressDialog.dismiss();
        }
    }
}
